package com.lemon.cloud.websocket.holder;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;

/**
 * @author HuangDS
 */
@Slf4j
public class MapSessionWebSocketHandlerDecorator extends WebSocketHandlerDecorator {
    private final SessionKeyGenerator sessionKeyGenerator;

    public MapSessionWebSocketHandlerDecorator(WebSocketHandler delegate, SessionKeyGenerator sessionKeyGenerator) {
        super(delegate);
        this.sessionKeyGenerator = sessionKeyGenerator;
    }

    @Override
    public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
        Object sessionKey = this.sessionKeyGenerator.sessionKey(session);
        log.info("connect sessionKey:{}",sessionKey);
        WebSocketSessionHolder.addSession(sessionKey, session);
    }

    @Override
    public void afterConnectionClosed(final WebSocketSession session, CloseStatus closeStatus) throws Exception {
        Object sessionKey = this.sessionKeyGenerator.sessionKey(session);
        WebSocketSessionHolder.removeSession(sessionKey);
    }
}
